<?php

if (!defined('BASEPATH'))
    exit('No direct script access allowed');

class Function_m extends CI_Model {

    function __construct() {
        parent::__construct();
    }
	
	  /**
     * *	店铺权限
     * *
     * */
	public function getshopnameauth()
	{
		$where = "";
		$shopname = $_COOKIE["shopname"];	//开通了权限的人员需要绑定店铺
		$shopname = unserialize($shopname);
		if($shopname)
		{
			$shopwhere = "";
				if(in_array('all',$shopname))	//可以查看所有店铺的订单
				{
				
				}else{
					$where.= " AND (";
					$shopwhere.=" AND (";
					foreach($shopname as $key=>$name)
					{
						if($key>0)
						{
							$or = " or";
						}
						$where.=" $or shopname = '".$name."'";
						$shopwhere.=" $or name = '".$name."'";
					}
					$where.=") ";
					$shopwhere.=") ";
				}
		
		}else{
			$where.= " AND shopname ='999'";//查询一个不存在的店铺
		}

		return $where;
	
	}

    /**
     * *	查询某个数据库单条记录
     * *
     * */
    public function getdatabasesdetail($databases, $where = '', $field = '*', $orderby = '') {
        //$this->db->select('*');
        //$this->db->where('id',3);
        //$this->db->where_in('id', 3);	
        //$query = $this->db->get('d_group');	
        //$list =  $query->result_array();
        $rs = $this->db->get_one("SELECT $field FROM $databases WHERE 1 $where $orderby ");


        return $rs;
    }

    /**
     * *	查询某个数据库多条记录
     * *
     * */
    public function getdatabaseslist($databases, $where = '', $field = '*', $orderby = '') {
        $query = $this->db->query("SELECT $field FROM $databases WHERE 1 $where $orderby");
        $dates = $query->result_array();
        return $dates;
    }

    /**
     * *	查询数据库并翻页
     * *
     * */
    public function getalllist($database, $where, $page = 1, $if_csv = 0, $pageSize = 100, $orderbys = '',$field='*',$join='') {
        if (!$orderbys) {
            $orderbys = " order by id desc";
        }
        //$sql = "SELECT $field FROM  $database WHERE 1";
        //$sql .= $where;
		//new add 5-18
		$sql = "SELECT $field FROM $database ";
		if($join){
			$sql.= $join;
		}
		$sql.= " WHERE 1 ";
		$sql.=$where;
        if ($page != null) {
            $offset = ($page - 1) * $pageSize;
            $limit = " LIMIT $pageSize OFFSET $offset";
        }
		if($if_csv)
		{
			$wheresql = $sql.$orderbys;
		}else{
			$wheresql = $sql . $orderbys . $limit;
		}

        $sqlCount = $sql.$orderbys;
        $query2 = $this->db->query($sqlCount);
        $allCount = $query2->num_rows();		
        $query = $this->db->query($wheresql);
        $dates = $query->result_array();
        return array('list' => $dates, 'total' => $allCount);
    }

    /**
     * 写文件函数
     * */
    function write_file($filename, $data, $method = "rb+", $iflock = 1) {

        @touch($filename);
        @chmod($filename, 0777);
        $handle = @fopen($filename, $method);
        if (!$handle && !strstr($filename, 'cache/label_cache')) {
            echo "此文件不可写:$filename";
            die;
        }
        if ($iflock) {
            @flock($handle, LOCK_EX);
        }
        @fputs($handle, $data);
        if ($method == "rb+")
            @ftruncate($handle, strlen($data));
        @fclose($handle);
        @chmod($filename, 0777);

        if (is_writable($filename)) {
            return 1;
        } else {
            return 0;
        }
    }

    /*
     * 读取部门表数据
     */

    public function getDepartment() {

        return $this->db->query('select * from d_group')->result_array();
    }

    /*
     * 读取职务表数据
     */

    public function getClassId() {

        return $this->db->query('select * from db_classid')->result_array();
    }

    /** **********************************
     * 过滤替换特殊字符 函数
     * *************************************** */

    function ReplaceSpecialChar($C_char, $news = 0) {//过滤特殊字符
        $C_char = str_replace("'", "‘", $C_char); //替换英文单引号 '
		
        if ($news == 1) {
            $C_char = str_replace(",", "，", $C_char); //替换英文逗号,
            $C_char = str_replace("<", "《", $C_char); //替换英文小破折号<
            $C_char = str_replace(">", "》", $C_char); //替换英文小破折号>
            $C_char = str_replace("{", "《", $C_char); //替换英文大括号{
            $C_char = str_replace("}", "》", $C_char); //替换英文大括号}
            $C_char = str_replace("(", "《", $C_char); //替换英文小括号(
            $C_char = str_replace("）", "》", $C_char); //替换英文小括号）
        }
		if($news ==2)
		{
			 $C_char = str_replace("，", ",", $C_char); //替换英文逗号,
		}

        return $C_char; //返回处理结果
    }
	function myTrim($str)
	{
		$search = array(" ","　","\n","\r","\t","'"," ");
		$replace = array("","","","","","","");
		$str=str_replace($search, $replace, $str);
		return preg_replace("/[\s\v".chr(194).chr(160)."]+$/","",$str); 
	}

    function curlfunc($url, $post_data, $cookie_jar, $header = '') {
        $user_agent = "Mozilla/4.0 (compatible; MSIE 8.0; Windows NT 6.1; Trident/4.0; GTB7.5; SLCC2; .NET CLR 2.0.50727; .NET CLR 3.5.30729; .NET CLR 3.0.30729; Media Center PC 6.0; InfoPath.3; .NET4.0C; .NET4.0E)";
        $ch = curl_init();
        curl_setopt($ch, CURLOPT_URL, $url);
        curl_setopt($ch, CURLOPT_REFERER, $url);
        curl_setopt($ch, CURLOPT_COOKIEJAR, $cookie_jar);
        curl_setopt($ch, CURLOPT_COOKIEFILE, $cookie_jar);
        curl_setopt($ch, CURLOPT_USERAGENT, $user_agent);
        curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false);
        curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, 2);
        curl_setopt($ch, CURLOPT_POST, 1);
        curl_setopt($ch, CURLOPT_POSTFIELDS, $post_data);
        curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
        curl_setopt($ch, CURLOPT_HEADER, false);
		curl_setopt($ch, CURLOPT_HTTPHEADER, $header );
        curl_setopt($ch, CURLOPT_FOLLOWLOCATION, 1);
        $output = curl_exec($ch);
        if ($output === FALSE) {
			$err = curl_error($ch);
			 curl_close($ch);
			 return array("err"=>201,"txt"=>$err);
           
        }
		
        return $output;
    }

    public function mkdirpath($path) {

        if (is_dir($path)) {
            $isdir = 1;
        } else {
            mkdir($path, 0777,true);
            chmod($path, 0777);
            $isdir = 1;
        }

        return $isdir;
    }

    public function newupfile($name,$pathname='') {
        $picname = $_FILES[$name]['name'];
        $picsize = $_FILES[$name]['size'];

        if ($picname != "") {
            if ($picsize > 1024000) {
                echo '图片大小不能超过1M';
                exit;
            }
			$typename = pathinfo($picname);
            $type = ".".$typename["extension"];
			
			if($this->config->item('filesuffix'))
				{
					$webdb = $this->config->item('filesuffix');
				}else{
					 //$webdb = '.jpg .gif .bmp .png';
					$webdb = '.jpg .gif .bmp .png';
				}
			$arr_webdb = explode(" ", $webdb);
			//测试
			if(!in_array('.xls',$arr_webdb)){
				$arr_webdb[] = '.xls'; //new add
			}
			 if (!in_array($type, $arr_webdb)) {
				  echo '不允许上传的文件 ';
				  exit; 
			}
            $rand = rand(100, 999);
            $pics = date("YmdHis") . $rand . $type;
            //上传路径
            $file = dirname(__FILE__) . "/../../uploads/";
			
            $file2 = date("Ymd");
			if($pathname)$file2=$pathname."/".$file2;
            $this->mkdirpath($file . $file2);
            $pic_path = $file . $file2 . "/" . $pics;
            move_uploaded_file($_FILES[$name]['tmp_name'], $pic_path);
        }
        $size = round($picsize / 1024, 2);
        $arr = array(
            'name' => $picname,
            'pic' => $file2 . "/" . $pics,
            'size' => $size
        );
        return $arr;
    }
	/******上传多文件、图片**********/

	function uploadfile($upload_path,$goods_id,$type,$isthumbnail=0)
	{
		$str = array();
		$nums = count($_FILES["userfile"]["name"]);
		if(count($_FILES["userfile"]["name"])>0)
		{
			for($i=1;$i<=$nums;$i++)
			{
				$postfile["name"] =  $_FILES["userfile"]["name"][$i];
				$postfile["tmp_name"] =  $_FILES["userfile"]["tmp_name"][$i];
				$postfile["size"] =  $_FILES["userfile"]["size"][$i];
				if ($postfile["name"]) {
				 if($postfile["size"]> 505120000)
				 {
					 return array("st"=>312,'txt'=>'文件过大!'); 
				 }
					$postfile["name"]=preg_replace('/[\s+\']/','-',$postfile["name"]);
					if($this->config->item('filesuffix'))
					{
						$webdb = $this->config->item('filesuffix');
					}else{
						 $webdb = '.jpg .gif .bmp .png';
					}
					 $filetype = strtolower(strrchr($postfile["name"], "."));
					 if (!in_array($filetype, explode(" ", $webdb))) {
						return array("st"=>313,'txt'=>'不允许上传的文件!'); 
					} else {//文件类型正常 上传操作
						
						$filenames = explode($filetype,$postfile["name"]);
						$filenames = $filenames[0];
						$tempname =$filenames. $filetype;
						 $tempnameds = $type."_" . date("YmdHms_", time()) . rand(10, 99) . $filetype;
						 $newfile = $upload_path."/$tempnameds";
						
						$upfile = $postfile["tmp_name"];
						if (@move_uploaded_file($upfile, $newfile)) {
							@chmod($newfile, 0777);
							//存缩略图
							$upload_path_thumbnail = '/uploads/thumbnail/'.date("Ymd")."";
							$dirthumb = dirname(__FILE__) . "/../..".$upload_path_thumbnail;
							!is_dir($dirthumb) && @mkdir($dirthumb, 0755, true);
							if (file_exists($newfile) && $isthumbnail==0) {
								ini_set('gd.jpeg_ignore_warning', true);
								$this->load->library('image_lib');
								$configimg['image_library'] = 'gd2';
								$configimg['source_image'] =$newfile;
								$configimg['create_thumb'] = TRUE;
								$configimg['maintain_ratio'] = TRUE;
								$configimg['new_image'] =  $dirthumb."/". $tempnameds;
								$configimg['width']     = $this->config->item('resizeToWidth');
								$configimg['height']   = $this->config->item('resizeToHeight');
								$this->image_lib->initialize($configimg);
								if ( ! $this->image_lib->resize())
								{
									echo $this->image_lib->display_errors();
								}else{
									$this->image_lib->clear();
								}
							}

							$newfileiconv = iconv("gbk","utf-8",$tempname); 
							$str[$i][] = $newfileiconv;
							$str[$i][] = $postfile["size"];
							$str[$i][] = $newfile;
							$file_path = pathinfo($newfile);
							$str[$i][] = $upload_path_thumbnail."/". $file_path["filename"]."_thumb." .$file_path['extension'];
							
						}else{
							$str[$i][] = 3000003;
							$str[$i][] = 3000003;
							$str[$i][] = 3000003;
							$str[$i][] = 3000003;
						}
					}
				}
			}
			
			 if($str)
                {
	    		    return array("st"=>200,'txt'=>'上传成功','filename'=>$str);	
    	    	}
    	    	else 
    	    		return array("st"=>311,'txt'=>'上传失败!');	
		}

	}
	
	/*****************
	*** 读取所有配置信息
	***  
	****************/
	 function getconfig() {
        $sql = "SELECT * FROM web_config";
        $query = $this->db->query($sql);
        $dates = $query->result_array();
        foreach ($dates as $key => $rs) {
            $rsdb[$rs["c_key"]] = trim($rs[c_value]);
        }

        return $rsdb;
    }
	//更新核心设置缓存
    function write_config_cache($webdbs) {
        if (is_array($webdbs)) {
            foreach ($webdbs AS $key => $value) {
                $value = $this->fun->ReplaceSpecialChar($value);
                if (is_array($value)) {
                    $webdbs[$key] = $value = implode(",", $value);
                }
                $SQL2 .= "'$key',";
                $SQL .= "('$key', '$value', ''),";
            }
            $SQL = $SQL . ";";
            $SQL = str_Replace("'),;", "')", $SQL);


            $this->db->query(" DELETE FROM web_config WHERE c_key IN ($SQL2'') ");
            $this->db->query(" INSERT INTO web_config VALUES  $SQL ");
        }
        $writefile = "<?php if ( ! defined('BASEPATH')) exit('No direct script access allowed');\r\n";

        $sql = "SELECT * FROM web_config";
        $query = $this->db->query($sql);
        $dates = $query->result_array();
        foreach ($dates as $key => $rs) {
            $rs[c_value] = trim(addslashes($rs[c_value]));

            if ($rs["c_key"] == "pagecontent" || $rs["c_key"] == "pagecontent_en" || $rs["c_key"] == "aboutus" || $rs["c_key"] == "contect") {
                
            } else {
                $writefile .= "\$config['$rs[c_key]']='$rs[c_value]';\r\n";
            }
        }
        $down_path = dirname(__FILE__) . "/../config/";
        $this->fun->write_file($down_path . "webset.php", $writefile);
        if (!is_writable($down_path . "webset.php")) {
            die($down_path . "webset.php文件目录权限不可写,请仔细检查");
        }
    }

	/*******保存商品子类图*****/
	
	public function saveImages($goods_id,$i)
	{
		$goodsinfo = $this->fun->getdatabasesdetail('db_goods'," AND goods_id = '".$goods_id."'");
		$upload_path = 'uploads/goods/'.date("Ymd")."/".$goodsinfo['goods_parent_sku'];
		$dir = dirname(__FILE__) . "/../../".$upload_path;
		!is_dir($dir) && @mkdir($dir, 0755, true);
		$postfile["name"] =  $_FILES["userfile"]["name"][$i];
		$postfile["tmp_name"] =  $_FILES["userfile"]["tmp_name"][$i];
		$postfile["size"] =  $_FILES["userfile"]["size"][$i];
		if ($postfile["name"]) {
		 if($postfile["size"]> 505120000)
		 {
			 return array("st"=>312,'txt'=>'文件过大!'); 
		 }
			$postfile["name"]=preg_replace('/[\s+\']/','-',$postfile["name"]);
			if($this->config->item('filesuffix'))
			{
				$webdb = $this->config->item('filesuffix');
			}else{
				 $webdb = '.jpg .gif .bmp .png';
			}
			 $filetype = strtolower(strrchr($postfile["name"], "."));
			 if (!in_array($filetype, explode(" ", $webdb))) {
				return array("st"=>313,'txt'=>'不允许上传的文件!'); 
			} else {//文件类型正常 上传操作
				
				$filenames = explode($filetype,$postfile["name"]);
				$filenames = $filenames[0];
				$tempname =$filenames. $filetype;
				 $tempnameds = "goods_" . date("YmdHms_", time()) . rand(10, 99) . $filetype;
				 $newfile = $upload_path."/$tempnameds";
				$upfile = $postfile["tmp_name"];
				if (@move_uploaded_file($upfile, $newfile)) {
					$imgdata["goods_id"] = $goods_id;
					$imgdata["images_type"] = 1;
					$imgdata["images_url"] = $tempname;
					$imgdata["local_url"] = $newfile;
					$imgdata["filename"] = $filenames;
					$imgdata["filesize"] = $postfile["size"];
					$imgdata["createUser"] = $_COOKIE["username"];
					$imgdata["instime"] = time();
					$this->db->query($this->db->insert_string('db_goods_images', $imgdata));
				}

				return array("st"=>200,'txt'=>'不允许上传的文件!'); 
			}
		}

	}
    /*     * **********************************
     * 获取一维数组的最小值 函数
     * *************************************** */

    function getminarray($value) {
        $pos = array_search(min($value), $value);
        return $value[$pos];
    }

	/************************************
	* 多维数据指定某值排序 函数
	* print_r(multi_array_sort($arr,'age'));exit;
	*****************************************/
	function multi_array_sort($multi_array,$sort_key,$sort=SORT_ASC){
			if(is_array($multi_array)){
			  foreach ($multi_array as $row_array){
					if(is_array($row_array)){
					 $key_array[] = $row_array[$sort_key];
					}else{
					return false;
					}
					}
			}else{
					return false;
			}
	array_multisort($key_array,$sort,$multi_array);
	return $multi_array;
	}

	/************************************
	*提示
	@param str $errno  1、不提示直接跳转 2 只提示 3 提示ID 4\提示并跳转
	*****************************************/
	function phpalert($errno,$err,$name='',$url='')
	{
		if($url)
		{
			$msg = array("rsm"=>array("rsm"=>1,"url"=>$url),"errno"=>$errno,"err"=>$err);
		}else{
			$msg = array("rsm"=>NULL,"errno"=>$errno,"err"=>$err,"name"=>$name);
		}
		
		
		echo json_encode($msg);
		die;
	}

	/***************************
	**	获取Userinfo信息
	**
	****************************/
	function userinfo($t)
	{
		$where=  " AND id = '".$t."' OR name = '".$t."'";
		$userinfo = $this->getdatabasesdetail('d_user',$where);
		return $userinfo;
	}
	/***************************
	**	获取User列表
	****************************/
	function userlist($department=0,$classid=0)
	{
		if($classid)
		{
			$where.=" AND classid in($classid)";
		}
		if($department)
		{
			$where.=" AND department in($department)";
		}
		$where.=" AND type = 1";
		return $this->getdatabaseslist('d_user', $where, $field = '*', " order by id DESC");
	}
	
	
	function testpdf2png($PDF)
	{
		/*
		$pic = "/uploads/test/20170728/b646a2aedcc70dea44be6dfac0d48260.jpg";
		$Path1 = dirname(__FILE__) . "/../../";
		$Path2 = "/uploads/test/20170728";
		$Path = $Path1.$Path2;
		$newfile = $Path1.$pic;
	      if (file_exists($newfile)){
				$this->load->library('image_lib');
				$configimg['image_library'] = 'gd2';
				$configimg['source_image'] =$newfile;
				$configimg['quality'] =100;
				$configimg['create_thumb'] = TRUE;
				$configimg['maintain_ratio'] = TRUE;
				 $finame = '/'.md5($Key.time()).'.gif';
				 $Filename = $Path.$finame;
				$configimg['new_image'] =  $Filename;
				$configimg['width']     =500;
				$this->image_lib->initialize($configimg);
				if ( ! $this->image_lib->resize())
				{
					echo $this->image_lib->display_errors();
				}else{
					$this->image_lib->clear();
				}
			}
	  
	
		*/
	   if(!extension_loaded('imagick')){
		   return false;
	   }
	   $Path1 = dirname(__FILE__) . "/../../";
	   $Path2 = "/uploads/test/".date("Ymd");
	   $Path = $Path1.$Path2;
		!is_dir($Path) && @mkdir($Path, 0755, true);
	   if(!file_exists($PDF)){
	       echo 'is not exists';
		   return false;
	   }
	   $IM =new imagick();
	   $IM->setResolution(300,300);
	   $IM->setCompressionQuality(100);
	   $IM->readImage($PDF);
	   foreach($IM as $Key => $Var){
		    // $Var->cropThumbnailImage(382,762);
		   $Var->setImageFormat('jpg');
		   $finame = '/'.md5($Key.time()).'.jpg';
		   $Filename = $Path.$finame;
		   if($Var->writeImage($Filename)==true){
				echo $Path2.$finame;
		   }
	   }
	   /*
	  // $IM->setResolution(300,300);
       $IM->setResolution(300,300); //设置分辨率
		$IM->setCompressionQuality(100);//设置图片压缩的质量
		$IM->setBackgroundColor('#FFFFFF');
		//$IM->cropThumbnailImage(400,800,true);//设置图片压缩的质量
	   $IM->readImage($PDF);
	   foreach($IM as $Key => $Var){
		   $Var->cropThumbnailImage(400,800);
		   $Var->setImageFormat('png');
			
		   $finame = '/'.md5($Key.time()).'.png';
		   $Filename = $Path.$finame;
		   if($Var->writeImage($Filename)==true){
			   echo $Path2.$finame;
			   die;
		   }
	   }
	   */


	}

	/**************************
	**
	**	将PDF转换成图片
	**
	*************/
	function pdf2png($PDF,$savefile='sfexpress'){
	   if(!extension_loaded('imagick')){
		   return false;
	   }
	   $Path1 = dirname(__FILE__) . "/../../";
	   $Path2 = "/uploads/{$savefile}/".date("Ymd");
	   $Path = $Path1.$Path2;
		!is_dir($Path) && @mkdir($Path, 0755, true);
	   if(!file_exists($PDF)){
	       echo 'is not exists';
		   return false;
	   }
	   $IM =new imagick();
       if($savefile=='dhlexpress'){//增加分辨率使文字更清晰
            $IM->setResolution(280,280); 
       }else{
            $IM->setResolution(300,300); 
       }
	   $IM->setCompressionQuality(100);
	   $IM->readImage($PDF);
	   foreach($IM as $Key => $Var){
		   $Var->setImageFormat('jpg');
           /*if($savefile=='dhlexpress'){//做图片缩小
                $canvas=new Imagick();  
                $img = new Imagick();  
                $img->readImageBlob($Var);  
                $img->thumbnailImage( 600, 1200, true );  
                $canvas->addImage( $img );  
                $canvas->setImageDelay( $img->getImageDelay() ); 
                $Var=$canvas;
           }*/
           $Var->enhanceImage();//去噪点
		   $ors=rand(1000,9999).substr(time(),-5).substr(microtime(),2,5);
           $finame = '/'.$ors.md5($Key.time()).'.jpg';
		   $Filename = $Path.$finame;
		   if($Var->writeImage($Filename)==true){
			   $Return[]= $Path2.$finame;
		   }
	   }
	   return $Return;





	/*

	   if(!extension_loaded('imagick')){
		   return false;
	   }
	   $Path1 = dirname(__FILE__) . "/../../";
	   $Path2 = "uploads/sfexpress/".date("Ymd");
	   $Path = $Path1.$Path2;
		!is_dir($Path) && @mkdir($Path, 0755, true);
	   if(!file_exists($PDF)){
		   return false;
	   }
	   $IM =new imagick();
	   $IM->setResolution(300,300);
	   $IM->setCompressionQuality(100);
        $IM->enhanceImage(); //去噪点
	  // $IM->thumbnailImage(600,8);
	   $IM->readImage($PDF);
	   foreach($IM as $Key => $Var){
		   $Var->setImageFormat('png');

		   $finame = '/'.md5($Key.time()).'.png';
		   $Filename = $Path.$finame;
		   if($Var->writeImage($Filename)==true){
			   $Return[]= $Path2.$finame;
		   }
	   }
	   $IM->clear();
	   $IM->destroy();
	   return $Return;*/
	}
	
	/**************************
	** ALTER TABLE `db_goods_log` CHANGE `goods_id` `rc_id` INT(11) NOT NULL;
	ALTER TABLE `db_goods_log` CHANGE `types` `types` TINYINT(1) NOT NULL COMMENT '1更新商品2库存信息3订单日志';
	** 更新商品信息
	** type :1 更新商品内容 2 更新库存 3 、订单信息
	** $gid = 订单ID、商品ID
	*************/
	public function goods_update_log($gid,$content,$types=1,$old_data='',$new_data='',$username='')
	{
		$imgdata["goods_id"] = $gid;
		$imgdata["updatetime"] = date("Y-m-d H:i:s");
		$imgdata["createUid"] = $_COOKIE["userid"]?$_COOKIE["userid"]:0;
		$imgdata["types"] = $types;
		$imgdata["content"] = $content;
		$imgdata["createUser"] = $username?$username:$_COOKIE["username"];
		$imgdata["old_data"] = $old_data;
		$imgdata["new_data"] = $new_data;
		$this->db->query($this->db->insert_string('db_goods_log', $imgdata));
	}
	
	/**************************
	**
	** 删除文件
	*************/
	function delattfile($path)
	{	
		$attpath =dirname(__FILE__)."/../../".$path;
		if(file_exists($attpath))
		{
			unlink($attpath);
		}

		return 200;
	}
	/**************************
	** 导出xls文件
	 @param array $data 数据，二维数组，每条数据一条记录
	 $headers =array("编号","支出日期","开票日期","类型","项目名称","价格","数量","支出金额","描述","供应商","工号","部门","操作时间");
	 @param array $header 表头
	*************/
	
	function ouputexclePro($header,$datas,$sttitle='支出列表')
	{
		require_once BASEPATH.'../fuman/ClassesExcel/PHPExcel.php';
		if(empty($datas) || !is_array($datas)){
			 die("data must be a array");
		}
		$date = date("YmdHis");
		$fileName= "{$date}.xlsx";
		$objPHPExcel = new PHPExcel();
		//设置表头
		$key = ord("A");
		  foreach($header as $v){
			   $colum = chr($key);
			   if($key==91)
			   {
					$colum='AA';
			   }
			   if($key==92)
			   {
					$colum='AB';
			   }
			   $objPHPExcel->setActiveSheetIndex(0) ->setCellValue($colum.'1', $v);
			   $key += 1;
		 }
		/*****处理中间行**********/
		$keys = ord("A");
		 foreach($datas as $key => $value){
			$st = $key+2;
			
			foreach($value as $kst=> $r)
			 {
			    $colum = chr($kst+$keys);
				$stkye=$kst+$keys;
				if($stkye==91)
			   {
					$colum='AA';
			   }
			   if($stkye==92)
			   {
					$colum='AB';
			   }
				//$objPHPExcel->setActiveSheetIndex(0)->setCellValue($colum.$st,$r);
				$objPHPExcel->getActiveSheet()->setCellValueExplicit($colum.$st,$r,PHPExcel_Cell_DataType::TYPE_STRING);
			 }
			
		 }
		   $objPHPExcel->getActiveSheet() -> setTitle('列表');
		   $objPHPExcel-> setActiveSheetIndex(0);
		   $objWriter = PHPExcel_IOFactory::createWriter($objPHPExcel, 'Excel2007');
		   header('Content-Type: application/vnd.ms-excel');
		   header('Content-Type: application/octet-stream');
		   header('Content-Disposition: attachment; filename="' . $fileName . '"');
		   header('Cache-Control: max-age=0');
		   $objWriter -> save('php://output');
		   die;
	}

	function ouputexcle($header,$datas)
	{
		require_once BASEPATH.'../fuman/ClassesExcel/PHPExcel.php';
		
		if(empty($datas) || !is_array($datas)){
			 die("data must be a array");
		}
		
		$date = date("YmdHis");
		$fileName= "{$date}.xlsx";
		$objPHPExcel = new PHPExcel();
		
    //设置表头
	$key = ord("A");
	  foreach($header as $v){
	       $colum = chr($key);
	       $objPHPExcel->setActiveSheetIndex(0) ->setCellValue($colum.'1', $v);
		   $key += 1;
	 }
	 foreach($datas as $key => $value){
	    $key=$key+2;
		$objPHPExcel->setActiveSheetIndex(0)->setCellValue('A'.$key,$value['orderId']);
		$objPHPExcel->setActiveSheetIndex(0)->setCellValue('B'.$key,$value['backdealid']);
		$objPHPExcel->setActiveSheetIndex(0)->setCellValue('C'.$key,$value['goods_sku']);
		$objPHPExcel->setActiveSheetIndex(0)->setCellValue('D'.$key,$value['skuName']);
		$objPHPExcel->setActiveSheetIndex(0)->setCellValue('E'.$key,$value['customerName']);
		$objPHPExcel->setActiveSheetIndex(0)->setCellValue('F'.$key,$value['country']);
		$objPHPExcel->setActiveSheetIndex(0)->setCellValue('G'.$key,$value['engCountry']);
		$objPHPExcel->setActiveSheetIndex(0)->setCellValue('H'.$key,$value['shopId']);
		$objPHPExcel->setActiveSheetIndex(0)->setCellValue('I'.$key,$value['factoryl']);
		$objPHPExcel->setActiveSheetIndex(0)->setCellValue('J'.$key,$value['platformId']);
		$objPHPExcel->setActiveSheetIndex(0)->setCellValue('K'.$key,$value['descr']);
	}
   $objPHPExcel->getActiveSheet() -> setTitle('SetExcelName');
   $objPHPExcel-> setActiveSheetIndex(0);
   $objWriter = PHPExcel_IOFactory::createWriter($objPHPExcel, 'Excel2007');
   header('Content-Type: application/vnd.ms-excel');
   header('Content-Type: application/octet-stream');
   header('Content-Disposition: attachment; filename="' . $fileName . '"');
   header('Cache-Control: max-age=0');
   $objWriter -> save('php://output');
   die;
}
	/**************************
	** 保存商品库存
	** $storage 仓库名称
	** $goods_id 商品ID
	** $in_stock 入库数
	** $in_transit 在途数
	** $positions 仓位
	*************/
	public function savestock($goods_id,$storage,$in_stock,$in_transit,$positions='')
	{
		$rsdb = $this->getdatabasesdetail('db_goods_stock'," AND goods_id='".$goods_id."' AND storage_name='".$storage."'");
		if($rsdb)
		{
			if($positions)
			{
				$positionssql = " ,positions='".$positions."'";
			}

			$oldstock = $rsdb['stock']+ $in_stock;
			$sql = "UPDATE db_goods_stock set stock=$oldstock,in_transit=in_transit+'".$in_transit."' $positionssql where id='".$rsdb["id"]."'";
			$this->db->query($sql);
			if($in_stock)
			{
				$this->goods_update_log($goods_id,'更新'.$storage.'库存 ['.$in_stock.'] 原库存 ['.$rsdb['stock'].'] ',1,$rsdb["stock"],$in_stock);	//更新了库存
			}
			if($in_transit)
			{
				$this->goods_update_log($goods_id,'更新'.$storage.'在途 ['.$in_transit.']',1,$rsdb["in_transit"],$in_transit);	//更新了库存
			}
			if($positions)
			{
				$this->goods_update_log($goods_id,'更新'.$storage.'库位 ['.$positions.']',1,$rsdb["positions"],$positions);	//更新了库存
			}

		}else{
			$rsdb = $this->getdatabasesdetail('db_storage'," AND storagename='".$storage."'");
			
			
			$imgdata = "";
			$imgdata["goods_id"] = $goods_id;
			$imgdata["storage_name"] = $storage;
			$imgdata["storage_id"] = $rsdb["id"];
			$imgdata["stock"] = $in_stock?$in_stock:0;
			$imgdata["in_transit"] = $in_transit?$in_transit:0;
			$rsgoods = $this->getdatabasesdetail('db_goods'," AND goods_id='".$goods_id."'","g_supplier");
			if($rsgoods["g_supplier"] ==3)
			{
				$imgdata["positions"] = $positions;
			}else{
				$imgdata["positions"] = NULL;
			}
			$this->db->query($this->db->insert_string('db_goods_stock', $imgdata));
			//$this->goods_update_log($goods_id,'更新【'.$storage.'】库存 [ '.$in_stock.']',1,0,$in_stock);	//更新了库存
		
		}
	}

	/**************************
	***	记录数据库更新修改
	*** 前后值
	**** array postdata
	***************************/

	public function updatelog($table,$postdata,$where,$status='',$goods_id='')
	{
	
		
		foreach ($postdata as $key => $val) {
            $valstr[] = $key;
        }
		$feils = implode(",",$valstr);
		$content="";
		$rsdb = $this->db->get_one("SELECT $feils FROM $table where $where");
		if($rsdb["goods_name"] !=$postdata["goods_name"])
			$content.="原商品名:".$rsdb["goods_name"]." 更新为:".$postdata["goods_name"]."<br>";
		
		if($rsdb["en_goods_name"] !=$postdata["en_goods_name"])
			$content.="原英文名:".$rsdb["en_goods_name"]." 更新为:".$postdata["en_goods_name"]."<br>";
		if($rsdb["goods_brand"] !=$postdata["goods_brand"])
			$content.="原品牌:".$rsdb["goods_brand"]." 更新为:".$postdata["goods_brand"]."<br>";
		if($rsdb["g_costprice"] !=$postdata["g_costprice"])
		{
			$pricememo  = $this->input->post('pricememo');
			if($pricememo)
			{
				$memotext = "  修改原因：".$pricememo;
			}
			$content.="原成本:".$rsdb["g_costprice"]." 更新为:".$postdata["g_costprice"].$memotext."<br>";
		}
		

		if($rsdb["wages"] !=$postdata["wages"]){
			$content.="原工时:".$rsdb["wages"]." 更新为:".$postdata["wages"]."<br>";
			
			$goods_parent_sku = trim($rsdb["goods_parent_sku"]);
			$this->db->update("db_goods",array("wages"=>$postdata["wages"]),"goods_parent_sku='".$goods_parent_sku."'");

		}
		
		//分类信息修改
		
		if($rsdb['g_bigclassid'] !=$postdata["g_bigclassid"])
		{
			$goods_parent_sku = trim($rsdb["goods_parent_sku"]);
			$this->db->update("db_goods",array("g_bigclassid"=>$postdata["g_bigclassid"],"g_threeclassid"=>0),"goods_parentID='".$rsdb['goods_parentID']."'");
			$this->db->update("db_goods_parent",array("p_bigclassid"=>$postdata["g_bigclassid"],"p_threeclassid"=>0),"p_parent_id='".$rsdb['goods_parentID']."'");
			
		}

		//分类信息修改
		if($rsdb['g_secondclassid'] !=$postdata["g_secondclassid"])
		{
			$this->db->update("db_goods",array("g_secondclassid"=>$postdata["g_secondclassid"],"g_threeclassid"=>0),"goods_parentID='".$rsdb['goods_parentID']."'");
			$this->db->update("db_goods_parent",array("p_secondclassid"=>$postdata["g_secondclassid"],"p_threeclassid"=>0),"p_parent_id='".$rsdb['goods_parentID']."'");
		}

		//供货商
		if($rsdb['g_supplier'] !=$postdata["g_supplier"])
		{
			$this->db->update("db_goods",array("g_supplier"=>$postdata["g_supplier"]),"goods_parentID='".$rsdb['goods_parentID']."'");
			$this->db->update("db_goods_parent",array("p_supplier"=>$postdata["g_supplier"]),"p_parent_id='".$rsdb['goods_parentID']."'");
		}



		if($rsdb["bulkprice"] !=$postdata["bulkprice"])
		{
			$bulkpricepricememo  = $this->input->post('bulkpricepricememo');
			if($bulkpricepricememo)
			{
				$bulkpricepricememo = "  修改原因：".$bulkpricepricememo;
				$content.="原批量价:".$rsdb["bulkprice"]." 更新为:".$postdata["bulkprice"].$bulkpricepricememo."<br>";
			}
		}
			
		if($rsdb["g_procurement"] !=$postdata["g_procurement"])
		{
			$content.="原采购天数:".$rsdb["g_procurement"]." 更新为:".$postdata["g_procurement"]."<br>";
			$this->db->update("db_goods",array("g_procurement"=>$postdata["g_procurement"]),"goods_parentID='".$rsdb['goods_parentID']."'");
			$this->db->update("db_goods_parent",array("p_procurement"=>$postdata["g_procurement"]),"p_parent_id='".$rsdb['goods_parentID']."'");
		}
		
		if($rsdb["goods_sku"] !=$postdata["goods_sku"])
		{
			$content.="原SKU:".$rsdb["goods_sku"]." 更新为:".$postdata["goods_sku"]."<br>";
			//需要修改订单
			//$this->db->update("db_order_sell",array("goods_sn"=>$postdata["goods_sku"])," goods_sn='".$rsdb["goods_sku"]."'");
		}
			

		if($rsdb["g_inventory_day"] !=$postdata["g_inventory_day"])
		{
			$content.="原库存警戒天数:".$rsdb["g_inventory_day"]." 更新为:".$postdata["g_inventory_day"]."<br>";
			$this->db->update("db_goods",array("g_inventory_day"=>$postdata["g_inventory_day"]),"goods_parentID='".$rsdb['goods_parentID']."'");
			$this->db->update("db_goods_parent",array("p_inventory_day"=>$postdata["g_inventory_day"]),"p_parent_id='".$rsdb['goods_parentID']."'");
		}
		if($rsdb["g_weight"] !=$postdata["g_weight"])
			$content.="原重量:".$rsdb["g_weight"]." 更新为:".$postdata["g_weight"]."<br>";
		if($rsdb["g_sellprice"] !=$postdata["g_sellprice"])
			$content.="原卖价:".$rsdb["g_sellprice"]." 更新为:".$postdata["g_sellprice"]."<br>";
		if($rsdb["g_pd_declare_value"] !=$postdata["g_pd_declare_value"])
			$content.="原申报价值:".$rsdb["g_pd_declare_value"]." 更新为:".$postdata["g_pd_declare_value"]."<br>";
		if($postdata["g_sale_status"]){
			if($rsdb["g_sale_status"] !=$postdata["g_sale_status"])
			{
				if($status)
				{
					if($rsdb["g_sale_status"]==4 || $rsdb["g_sale_status"]==5)
					{
					
					}else{
						if($status[$rsdb["g_sale_status"]])
						{
							$content.="原销售状态:".$status[$rsdb["g_sale_status"]]." 更新为:".$status[$postdata["g_sale_status"]]."<br>";
						}else{
							$content.="原销售状态更新为:".$status[$postdata["g_sale_status"]]."<br>";
						}
					}
					
				}
			}
		}
			
		if($rsdb["g_checkman"] !=$postdata["g_checkman"])
			$content.="原开发:".$rsdb["g_checkman"]." 更新为:".$postdata["g_checkman"]."<br>";
		if($rsdb["g_buyer"] !=$postdata["g_buyer"])
			$content.="原采购:".$rsdb["g_buyer"]." 更新为:".$postdata["g_buyer"]."<br>";
		if($rsdb["standard"] !=$postdata["standard"])
			$content.="原质检标准:".strip_tags($rsdb["standard"])." 更新为:".strip_tags($postdata["standard"])."<br>";
		if($rsdb["memo"] !=$postdata["memo"])
			$content.="原备注:".$rsdb["memo"]." 更新为:".$postdata["memo"]."<br>";
		if($rsdb["fabricinfo"] !=$postdata["fabricinfo"])
			$content.="原面料:".$rsdb["fabricinfo"]." 更新为:".$postdata["fabricinfo"]."<br>";
		if($rsdb["cognatelist"] !=$postdata["cognatelist"])
			$content.="原子SKU:".$rsdb["cognatelist"]." 更新为:".$postdata["cognatelist"]."<br>";


		if($rsdb["g_costprice"] !=$postdata["g_costprice"])
		{
			$pricememo  = $this->input->post('pricememo');
			if($pricememo)
			{
				$memotext = "  修改原因：".$pricememo;
			}
			//如果修改了成本价，单独列表
			$text="原成本价: ".$rsdb["g_costprice"]." 更新为: ".$postdata["g_costprice"]. $memotext;
			$this->goods_update_log($goods_id,$text,4,$rsdb["g_costprice"],$postdata["g_costprice"]);	//更新成本价


			//成本改变，同步同类商品
			$goods_parent_sku = trim($postdata["goods_parent_sku"]);
			//$this->db->update("db_goods",array("g_costprice"=>$postdata["g_costprice"]),"goods_parent_sku='".$goods_parent_sku."'");
			
			//修改了成本，记录修改信息
			$this->insertsysstatistical('costprice',9,$goods_id,0,$text);
			
			
		}

		if($rsdb["bulkprice"] !=$postdata["bulkprice"])
		{
			$bulkpricepricememo  = $this->input->post('bulkpricepricememo');
			if($bulkpricepricememo)
			{
				$bulkpricepricememo = "修改原因：".$bulkpricepricememo;
			}
			$text="原关联价:".$rsdb["bulkprice"]." 更新为:".$postdata["bulkprice"].$bulkpricepricememo;
			$this->goods_update_log($goods_id,$text,5,$rsdb["bulkprice"],$postdata["bulkprice"]);	//更新关连价
			$goods_parent_sku = trim($postdata["goods_parent_sku"]);
			$this->db->update("db_goods",array("bulkprice"=>$postdata["bulkprice"]),"goods_parent_sku='".$goods_parent_sku."'");
			$this->db->update("db_goods_parent",array("bulkprice"=>$postdata["bulkprice"]),"p_parent_sku='".$goods_parent_sku."'");
			$this->insertsysstatistical('costprice',10,$goods_id,0,$text);
		}
			


		if($content)
		{
			return $content;
		}
		
	}
	/**
	  +----------------------------------------------------------
	 * 获取商品状态列表
	  +----------------------------------------------------------
	 * @param types  ('status','stock','sale');
	 * @return array
	  +----------------------------------------------------------
	 */
	public function get_sys_goods_status($item='')
	{
		if($item=='')
		{
			$item = 'sys_goods_status';
		}
		if($this->config->item($item))
		{
			$sys_goods_status = $this->config->item($item);
			$statusList = explode("\r\n",$sys_goods_status);
			foreach($statusList as $key=>$rs)
			{
				if($rs){
					$list = explode("|",$rs);
					$k = intval($list[0]);
					$newlist[$k]= trim($list[1]);
				}

			}
			return $newlist;
		}else{
			return array("1" => '新品', "2" => '正常销售', "3" => '重点产品', "5" => '清仓', "6" => '暂停销售', "4" => '停售(平台下架)');
		}
	}
	/**
	  +----------------------------------------------------------
	 * 更新系统统计信息
	  +----------------------------------------------------------
	 * @param types  ('status','stock','sale');
	 +----------------------------------------------------------
	 * @param status  重点产品，清仓，下架，上架，暂停销售
	  +----------------------------------------------------------
	 * @param pid  parentID或者goods_ID
	  +----------------------------------------------------------
	 * @param parent  1或者0 1表示主SKU下的所有，0单个SKU
	  +----------------------------------------------------------
	 * @return string
	  +----------------------------------------------------------
	 */
	public function insertsysstatistical($types,$status,$pid,$parent,$statuslist='')
	{
		if($statuslist=='')
		{
			$statuslist = $this->get_sys_goods_status();
		}
		switch ($types) {
			case 'status':	//修改状态信息
				if($status==4 || $status==5 || $status==6 || $status==7 || $status==8 || $status==2 || $status==9)
				{
					if($parent==1)	//同pid的商品都改变状态
					{
						$goodslist = $this->db->get_where('db_goods',array("goods_parentID"=>$pid))->result_array();
					}else{
						$goodslist = $this->db->get_where('db_goods',array("goods_id"=>$pid))->result_array();
					}
					$goodsstr="";
					foreach($goodslist as $key=>$rs)
					{
						$this->db->delete('db_sys_workbench'," types in(2,4,5,6,7,8,9) AND number_id='".$rs['goods_id']."'");//先删除之前的记录，再插入最近统计
						$postdata="";
						$postdata['number_id'] = $rs['goods_id'];
						$postdata['number_sn'] = $rs['goods_sku'];
						$postdata['number_name'] = $rs['goods_name'];
						$postdata['types'] = $status;
						$postdata['oper'] = $_COOKIE['userid']?$_COOKIE['userid']:0;
						$postdata['operName'] = $_COOKIE['username']?$_COOKIE['username']:"SYSTEM";
						$postdata['opertime'] = date("Y-m-d H:i:s");
						$postdata['memo'] = "";
						$this->db->insert('db_sys_workbench',$postdata);
						$goodstr=$goodstr.$rs['goods_sku'].",";
					}
					//给所有销售消息提醒
					/*
					$Userlist = $this->db->select('name')->get_where('d_user',array('department'=>3,'type'=>1))->result_array();
					//$Userlist = $this->db->select('name')->get_where('d_user',array('id'=>295,'type'=>1))->result_array();
					$randid = $this->message->getMessageNums();	//获取当前存储的条数	
					foreach($Userlist as $rs)
					{
						$postMessageData["message_type"] = $this->message->getMessageType(9);	//商品状态调整
						$message = $_COOKIE["username"]."[".date("Y-m-d H:i:s")."]"."对商品编号：".$goodstr;
						$message.="调整状态为【".$statuslist[$status]."】";
						$postMessageData["message"] = $message;
						$postMessageData["message_toName"] = $rs['name'];
						$postMessageData["isread"] =  $randid;
						if($status<9)
						{
							$postMessageData["url"] = "/welcome/ajaxbutton?op=showMoreGoods&types={$status}";
						}else{
							$postMessageData["url"] = '/welcome';
						}
						$this->fun->saveMessage($postMessageData);
					}*/

				}
				
				break;
			case 'stock':	//库存信息
		
				break;
			case 'sale':
				break;		//商品关联信息

			case 'costprice':
				$goodslist = $this->db->get_where('db_goods',array("goods_id"=>$pid))->result_array();
				foreach($goodslist as $key=>$rs)
				{
					$this->db->delete('db_sys_workbench'," types in($status) AND number_id='".$rs['goods_id']."'");//先删除之前的记录，再插入最近统计
					$postdata="";
					$postdata['number_id'] = $rs['goods_id'];
					$postdata['number_sn'] = $rs['goods_sku'];
					$postdata['number_name'] = $rs['goods_name'];
					$postdata['types'] = $status;
					$postdata['oper'] = $_COOKIE['userid'];
					$postdata['operName'] = $_COOKIE['username'];
					$postdata['opertime'] = date("Y-m-d H:i:s");
					$postdata['memo'] = $statuslist;
					$this->db->insert('db_sys_workbench',$postdata);
				}
				break;
		}
	}
	/**
	  +----------------------------------------------------------
	 * 获取货币类型
	  +----------------------------------------------------------
	 * @param string    $name
	  +----------------------------------------------------------
	 * @return string
	  +----------------------------------------------------------
	 */
	public function getmoneyrate($name='')
	{
		if($name)
		{
			$moneyrate = $this->fun->getdatabasesdetail("d_moneyrate", " AND name='" . trim($name) . "'");
		}else{
			$moneyrate = $this->fun->getdatabaseslist("d_moneyrate");
		}
		return $moneyrate;		
	
	}




	/**
	  +----------------------------------------------------------
	 * 生成随机字符串
	  +----------------------------------------------------------
	 * @param int       $length  要生成的随机字符串长度
	 * @param string    $type    随机码类型：0，数字+大小写字母；1，数字；2，小写字母；3，大写字母；4，特殊字符；-1，数字+大小写字母+特殊字符
	  +----------------------------------------------------------
	 * @return string
	  +----------------------------------------------------------
	 */
		function randCode($length, $type = 0) {
			if($length ==999)
			{
				$length=mt_rand(3,10);
			}
			$arr = array(1 => "0123456789", 2 => "abcdefghijklmnopqrstuvwxyz", 3 => "ABCDEFGHIJKLMNOPQRSTUVWXYZ");
			if ($type == 0) {
				array_pop($arr);
				$string = implode("", $arr);
			} elseif ($type == "-1") {
				$string = implode("", $arr);
			} else {
				$string = $arr[$type];
			}
			$count = strlen($string) - 1;
			$code = '';
			for ($i = 0; $i < $length; $i++) {
				$code .= $string[rand(0, $count)];
			}
			return $code;
		}

	/**
	  +----------------------------------------------------------
	 * 消息队列
	  +----------------------------------------------------------
	 * @param array       $message  消息内容
	  +----------------------------------------------------------
	 * @return string
	  +----------------------------------------------------------
	 */
	function saveMessage($postMessageData)
	{
		$username = $this->fun->userinfo($postMessageData["message_toName"]);
		$postMessageData["message_toID"] = $username["id"]?$username["id"]:295;	//接收对象ID
		$postMessageData["message_formID"] = $_COOKIE["userid"];
		$postMessageData["message_formName"] =  $_COOKIE["username"];
		$this->message->saveMessage($postMessageData);
	}
	 /**
	  +----------------------------------------------------------
	 * 将数组转换成xml
	  +----------------------------------------------------------
	 * * @param mixed $data 数据
	 * @param string $encoding 数据编码
	 * @param string $root 根节点名
	 * @return string
	  +----------------------------------------------------------
	 */
	function xml_encode($data, $encoding='utf-8', $root='think') {
		$xml    = '<?xml version="1.0" encoding="' . $encoding . '"?>';
		$xml   .= '<' . $root . '>';
		$xml   .= $this->data_to_xml($data);
		$xml   .= '</' . $root . '>';
		return $xml;
	}
	/**
	 * 数据XML编码
	 * @param mixed $data 数据
	 * @return string
	 */
	function data_to_xml($data) {
		$xml = '';
		foreach ($data as $key => $val) {
			is_numeric($key) && $key = "item id=\"$key\"";
			$xml    .=  "<$key>";
			$xml    .=  ( is_array($val) || is_object($val)) ? $this->data_to_xml($val) : $val;
			list($key, ) = explode(' ', $key);
			$xml    .=  "</$key>";
		}
		return $xml;
	}
	/**
	  +----------------------------------------------------------
	 * 判断是否为定制的商品信息
	  +----------------------------------------------------------
	 * @return array
	  +----------------------------------------------------------
	 */
	public function getfactorygoodsku($goodsku)
	{
		$factorycode = $this->factorycode();
		if(is_numeric($goodsku) && preg_match('|^\d{8}$|',$goodsku))	//数字并且8位SKU并且11 12开头
		{
			$goodscode  = substr($goodsku,0,2);//取开头2位数
			if(in_array($goodscode,$factorycode))	//是否存在在工厂code
			{
				return true;	//定制衣服按成本价计算
			}else{
				return false;
			}
		}
	}
	/**
	  +----------------------------------------------------------
	 * 获取工厂的code信息,11,12或者13
	  +----------------------------------------------------------
	 * @return array
	  +----------------------------------------------------------
	 */

	public function factorycode()
	{
		$rsdb = $this->db->get_where("db_factory","code >0")->result_array();
		foreach($rsdb as $key =>$rs)
		{
			$factorycode[] = $rs["code"];	//工厂编号
		}

		return $factorycode;
	}
	/**
	  +----------------------------------------------------------
	 * 获得五位关联SKU信息
	  +----------------------------------------------------------
	 * @param string       $sku  父sKU号
	 @ ya  1亚洲 0 通用或者欧洲
	  +----------------------------------------------------------
	 * @return string
	  +----------------------------------------------------------
	 */

	function getlinktosku($sku,$type = 0,$ya=0)
	{
		$factorycode = $this->factorycode();
		
		if(is_numeric($sku) && preg_match('|^\d{8}$|',$sku))	//数字并且8位//判断是否是符合导订的要求 //8位SKU并且11 12开头
		{
			$goodscode  = substr($sku,0,2);
			if(in_array($goodscode,$factorycode))
			{
				//是工厂订制的衣服
				if($type ==1)
				{
					//重复自建五位SKU
					$newsku = $this->randCode(5,1);
				}else{
					$newsku="";
					//$newsku.=  substr($sku,0,1);
					$newsku.=  substr($sku,-3,4);
					$newsku = "16".$newsku;
				}

				if($ya==1)	//亚洲款 前面改成19
				{
					$newskust =  substr($sku,-3,4);
					$newsku = "19".$newskust;
				}

				$res = $this->fun->getdatabasesdetail('db_goods' ," AND goods_sku REGEXP '$newsku'");	//匹配是否包含该生成的SKU,如果有重复的即重新自建
				if($res)
				{
					$newsku = $this->getlinktosku($sku,1);
				}
				
				//如果子SKU中包含了，也需要重新换一个

			}
		}

		return $newsku;
	}
	

	


	/**
	  +----------------------------------------------------------
	 * 库存处理
	  +----------------------------------------------------------
	 * @param int   $orderid 订单ID
	 * @param int   $goodsID 商品ID
	 * @param int   $storage_id  库存ID
	 * @param int   $stock       库存数
	 * @param bool  $type  0减库存  1 加库存
	   库存加减必须进行事务处理
	  +----------------------------------------------------------
	 * @return bool
	  +----------------------------------------------------------
	 */
	function inventory($orderid,$goodsID,$storage_id,$stock,$type)
	{
		//目前只考虑到订单的扫单发货，库存的
		
		if($type==1)
		 {
			$txt = "增加库存";
			$where = "stock = stock+$stock";
		 }else{
			 $txt = "减少库存";
			$where = "stock = stock-$stock";
		 }
		
		$rsdb = $this->getdatabasesdetail("db_goods_stock"," AND goods_id='".$goodsID."' AND storage_id = '".$storage_id."'");
		$rsgoods =$this->getdatabasesdetail("db_goods"," AND goods_id='".$goodsID."'"," goods_sku ");
		
		//如果遇到定制的衣服，工厂8位SKU，不减库存
		if($rsgoods['goods_sku'])
		{
			if($this->getfactorygoodsku($rsgoods['goods_sku']))	//是定制商品,不需要减库存
			{
				 $rval= "定制商品:{$rsgoods[goods_sku]},不扣库存！";
				 $this->goods_update_log($orderid, $rval, 3);    //日志
					//定制商品也需要累积销量
				  $sql = "UPDATE db_goods SET saleNum = saleNum+$stock where goods_id = '".$goodsID."'";
				  $this->db->query($sql);
				 return;
			}
		}

			$this->db->trans_begin();	//事务开始
			if($rsdb)
			{
				$storagename = $rsdb["storage_name"];
				$sql = "UPDATE db_goods_stock SET $where where goods_id = '".$goodsID."' AND storage_id = '".$storage_id."'";
				$this->db->query($sql);
			}else{
				$storage = $this->getdatabasesdetail("db_storage"," AND id='".$storage_id."'");
				$storagename = $storage["storage_name"];
				$rsdb["stock"] = 0;
				$sql = "INSERT INTO db_goods_stock SET goods_id = '".$goodsID."',storage_id='".$storage_id."',storage_name='".$storage["storagename"]."',in_transit=0, $where ";
				$this->db->query($sql);
			}
	 
		//日志部分需要考虑阿米巴的需求
		
		if($type==1)
		{
			$new_data = $rsdb["stock"] +$stock;
		}
		else{
			$new_data = $rsdb["stock"] -$stock;
		}
		if($orderid){
			$order = $this->getdatabasesdetail("db_order_list"," AND order_id ='".$orderid."'"," order_sn,shopid");
			$content=  "修改[$storagename]库存：订单<a href='/orderlist/editorder?sn=$order[order_sn]' target=_thank> $order[order_sn]</a> 发货,原来库存[".$rsdb["stock"]."] 现在库存[ ".$new_data." ]<br>";
			$this->goods_stock_log($orderid,$goodsID,$order["shopid"],$content,$stock,$type,$rsdb["stock"],$new_data);    //库存日志
			$this->goods_update_log($goodsID, $content, 1,$rsdb["stock"],$new_data);    //日志
			
			 $rval= "扣除[$storagename]产品ID:{$rsgoods[goods_sku]}库存,原库存[".$rsdb["stock"]."]个,扣除发货[".$stock."]个,现在库存[ ".$new_data." ]";
			 $this->goods_update_log($orderid, $rval, 3);    //日志
			if($type==0)
			{
			 //存商品的总销量
			 $sql = "UPDATE db_goods SET saleNum = saleNum+$stock where goods_id = '".$goodsID."'";
			 $this->db->query($sql);
			}
		}
		 



	   if ($this->db->trans_status() === FALSE)
		{
			$this->db->trans_rollback();
		}
		else
		{
			$this->db->trans_commit();
		}
	}
	



	/*
		减少库存
		 * @param int   $type 0减库存，1加库存
*/
	public function goods_stock_log($orderid,$goodsID,$shopid,$content,$stock,$type,$old_data='',$new_data='',$username='',$fba=0)
	{
		$imgdata="";
		$imgdata["order_id"] = $orderid;
		$imgdata["goods_id"] = $goodsID;
		$imgdata["shopid"] = $shopid;
		$imgdata["type"] = $type;
		$imgdata["stock"] = $stock;
		$imgdata["updatetime"] = date("Y-m-d H:i:s");
		$imgdata["createUid"] = $_COOKIE["userid"]?$_COOKIE["userid"]:0;
		$imgdata["content"] = $content;
		$imgdata["createUser"] = $username?$username:$_COOKIE["username"];
		$imgdata["old_data"] = $old_data;
		$imgdata["new_data"] = $new_data;
		$imgdata['isfba'] = $fba;
		$this->db->query($this->db->insert_string('db_goods_stock_log', $imgdata));
	}

	/**
	  +----------------------------------------------------------
	 * 获取商品成本价
	  +----------------------------------------------------------
	 * @param int   $orderid 订单ID
	   进来的商品如果是11、12开头的工厂商品，用成本价
	   如果是关联商品，用关联价
	   如果是外采购商品 用成本价
	  +----------------------------------------------------------
	 * @return bool
	  +----------------------------------------------------------
	 */
	 public function get_Goods_costprice($goods_sku)
	 {
		$goods_sku = trim($goods_sku);
		$rgoods = $this->getdatabasesdetail("db_goods"," AND goods_sku='".$goods_sku."'");
		if($rgoods)
		{
			/*****************成本价计算方式********
			**  11、12开头定制的衣服按成本价计算
			**  批量的sku 按关联价计算
			**  外采购的衣服按成本价计算
			*********************************/
			$costprice = 0;
			if($this->getfactorygoodsku($goods_sku))	//是定制商品
			{
				$costprice = $rgoods["g_costprice"];	//定制衣服按成本价计算
			}else{
				if(is_numeric($rgoods["goods_parent_sku"]) && preg_match('|^\d{8}$|',$rgoods["goods_parent_sku"]))	//数字并且8位SKU并且11 12开头
				{
					$factorycode = $this->factorycode();
					$goodscodes  = substr($rgoods["goods_parent_sku"],0,2);//取开头2位数
					if(in_array($goodscodes,$factorycode))	//是否存在在工厂code
					{
						if($rgoods["bulkprice"]>0)
						{
							$costprice = $rgoods["bulkprice"];	//批量按关联价计算
						}else{
							$costprice = $rgoods["g_costprice"];	//批量按关联价计算
						}
					}else{
						$costprice = $rgoods["g_costprice"];	//如果没有关联价直接用成本价
					}
				}else{
					$costprice = $rgoods["g_costprice"];
				}
			}
		}
		return $costprice;
	 }
	
	/**
	  +----------------------------------------------------------
	 * 获取商品库存信息
	  +----------------------------------------------------------
	  +----------------------------------------------------------
	 * @return int
	  +----------------------------------------------------------
	 */
	public function getstock($goods_id)
	{
		//仓库信息
		$stock = $this->getdatabaseslist("db_goods_stock A LEFT JOIN db_storage B on A.storage_id=B.id"," AND B.is_show=1 and A.goods_id='".$goods_id."'","A.*");
		
		//$stock = $this->db->get_where("db_goods_stock",array("goods_id"=>$goods_id))->result_array();
		foreach($stock as $key=>$rs)
		{
//			if($rs["waitnum"] >0)
//			{
//				$stock[$key]["waitday"] = date("Y-m-d",$rs['waitday']);
//			}
			if($rs['waitday']>0){
				$stock[$key]["waitday"] = date("Y-m-d",$rs['waitday']);
			}else{
				$stock[$key]["waitday"]="";
			}
		}
		return $stock;
	}
	/**
	  +----------------------------------------------------------
	 * 通过大分类，小分类自动生成SKU编号
	  +----------------------------------------------------------
	 * @param INT bigclassID   商品大类
	 * @param INT secondclassID  商品小类
	 * @param int 6   自动生成几位
	  +----------------------------------------------------------
	 * @return 自动编号
	  +----------------------------------------------------------
	 */
	function autoskunumber($bigclassID,$secondclassID,$num = 4)
	{
		$Bigcode = $this->getdatabasesdetail("db_goods_category"," AND id='".intval($bigclassID)."'");
		$secondcode = $this->getdatabasesdetail("db_goods_category"," AND id='".intval($secondclassID)."'");
		$SKUCODE = "";
		if($Bigcode['sku_code'] && $secondcode['sku_code'])
		{
			$SKUCODE.= $Bigcode['sku_code'];
			$SKUCODE.= $secondcode['sku_code'];
			$SKUCODE.= $this->randCode($num,1);

			$res = $this->fun->getdatabasesdetail('db_goods' ," AND goods_sku REGEXP '$SKUCODE'");	//匹配是否包含该生成的SKU,如果有重复的即重新自建
			if($res)
			{
				$SKUCODE = $this->autoskunumber($bigclassID,$secondclassID,$num+1);
			}else{
				$res = $this->fun->getdatabasesdetail('db_external_buy' ," AND sku REGEXP '$SKUCODE'");	//匹配是否包含该生成的SKU,如果有重复的即重新自建
				if($res)
				{
					$SKUCODE = $this->autoskunumber($bigclassID,$secondclassID,$num);
				}
			}
			return $SKUCODE;
		}
	}


	/**
	  +----------------------------------------------------------
	 * 获取某个时间段内SKU的销量
	  +----------------------------------------------------------
	 * @param INT goods_id   商品ID
	 * @param INT startime  开始时间
	 * @param endtime   结束时间
	  +----------------------------------------------------------
	 * @return int 销量
	  +----------------------------------------------------------
	 */
	 public function get_goods_sale($goods_id,$startime,$endtime,$country='',$cang='')
	{
		if($country)
		{
			$where = " AND B.country_cn = '".$country."'";
		}
		if($cang)
		{
			$where.=" AND shipping_status = $cang";
		}
		$sql = "SELECT sum(goods_number) as goods_number FROM db_order_sell A LEFT JOIN db_order_list B ON A.order_id = B.order_id WHERE goods_id in($goods_id) AND B.dates>='".$startime."' AND B.dates <='".$endtime."' $where AND (B.order_status =4 or B.order_status =5 or  B.order_status =2 or  B.order_status =3)";
	
		$res = $this->db->get_one($sql);
		if(!$res['goods_number'])
			return 0;
		else{
			return $res['goods_number'];
		}
	}

	/**
	  +----------------------------------------------------------
	 * 获取某个时间段内FBA SKU的销量
	  +----------------------------------------------------------
	 * @param INT goods_id   商品ID
	 * @param INT startime  开始时间
	 * @param endtime   结束时间
	  +----------------------------------------------------------
	 * @return int 销量
	  +----------------------------------------------------------
	 */
	 public function get_goods_fba_sale($goods_id,$startime,$endtime,$country='')
	{
		 if($country)
		{
			$where = " AND B.country_cn = '".$country."'";
		}
		
		$sql = "SELECT sum(ordernum) as goods_number FROM db_amzordertmpsell A LEFT JOIN db_amzordertmp B ON A.ordertmpid = B.id WHERE goods_id in($goods_id) AND B.dates>='".$startime."' AND B.dates <='".$endtime."' AND status =1 $where";
		$res = $this->db->get_one($sql);
		if(!$res['goods_number'])
			return 0;
		else{
			return $res['goods_number'];
		}
	}

	 /***************************
	 ** 自动修正商品的重量信息
	 ** 扫单出货读取最近十笔单个SKU的订单，取平均值
	 *********************************/
	public function getgoodsweigth($resgoods,$neednum=10)
	{
		$isup=0;//不执行
		$log = $this->getdatabasesdetail("db_goods_log"," AND  goods_id ='".$resgoods["goods_id"]."' AND content like '%最新10个订单平均重量%' ");
		if(!$log)
		{
			$isup=1;
		}else{
			//大于三个月则更新，否则不更新
			$stime = strtotime($log['updatetime']);
			if(time()-$stime>=7776000)
			{
				$isup =1;
			}else{
				return false;
			}
		}
		if($isup==1){
			$resbactionGoods = $this->getdatabaseslist("db_order_batchexpress"," AND  skulist like '%,".$resgoods["goods_sn"].",%' AND skuNum=1",'id'," ORDER BY id DESC LIMIT 10 ");
			$nums =count($resbactionGoods);
			if($nums>=$neednum)
			{
				$bactorderID="";
				foreach($resbactionGoods as $sor)
				{
					$bactorderID[]= $sor['id'];
				}
				$bactorderID  = implode(",",$bactorderID);
				$rsdbWeth = $this->db->get_one("select sum(batch_orderweight) as weigth  from db_order_batchexpress where id in($bactorderID)");
				$weigth = $rsdbWeth["weigth"];
				$junweith = intval($weigth/$nums);
				if($junweith>0)
				{
					$rsGoodsstr = $this->getdatabasesdetail("db_goods"," AND goods_id=".$resgoods["goods_id"]);
					if($rsGoodsstr["g_weight"] != $junweith )
					{
						$postdata="";
						$postdata["g_weight"] = $junweith;
						$this->db->update("db_goods",$postdata,"goods_id=".$resgoods["goods_id"]);
						if($log){
							$this->db->delete("db_goods_log","id=".$log['id']);
						}
						$rval= "最新10个订单平均重量->{$junweith} 原重量->{$rsGoodsstr[g_weight]}<br>";
						$this->goods_update_log($resgoods["goods_id"], $rval, 1);    //日志
					}
				}
			}
		}

		return true;
	}
	
	/**
	  +----------------------------------------------------------
	 * 还原工厂订单的五位SKU信息
	  +----------------------------------------------------------
	 * @param 
	 * @param 
	 * @param 
	  +----------------------------------------------------------
	 * @return int
	  +----------------------------------------------------------
	 */
	public function backupfactorylinkproduct($orderid)
	{
		$rsdb = $this->fun->getdatabasesdetail('db_factory_order'," AND orderId='".$orderid."' AND isform = 1");
		
		if($rsdb){
			$tradeid = $rsdb['mabangorderid'];
			$orderID = $rsdb['id'];
			$rsdbSell = $this->fun->getdatabasesdetail('db_factory_sell'," AND orderId='".$orderID."' AND custom = 1");
			if($rsdbSell){
				$sku  = $rsdbSell['goods_sku'];
				$model = $rsdbSell['model'];
				$gender1 = $rsdbSell['gender1'];
				$custom  = $rsdbSell['custom'];	
				$size    = $rsdbSell['size'];

				if($size=='25') $sizestr = "XXS";
				if($size=='30') $sizestr = "XS";
				if($size=='35') $sizestr = "S";
				if($size=='40') $sizestr = "M";
				if($size=='45') $sizestr = "L";
				if($size=='50') $sizestr = "XL";
				if($size=='55') $sizestr = "XXL";
				if($size=='60') $sizestr = "XXXL";

				if($gender1 == 1)
				{
					$sex = "男性";
				}
				if($gender1 == 2)
				{
					$sex = "女性";
				}
				if($gender1 == 3)
				{
					$sex = "通用";
				}
				if($model == 1)
				{
					$model = "欧美";
				}
				if($model == 2)
				{
					$model = "亚洲";
				}

				$goodslist = $this->fun->getdatabasesdetail("db_goods"," AND goods_parent_sku = '".$sku."' AND goods_sku !='".$sku."'","GROUP_CONCAT(goods_id) as goodsID");
				
				if($goodslist["goodsID"])
				{
					$goodsID = $goodslist["goodsID"];

					  $query = $this->db->query("SELECT * from db_goods_attr where 1  AND (attr_value='".$sex."' or attr_value='通用') AND attr_id = 1 and goods_id in (SELECT goods_id FROM db_goods_attr WHERE 1 AND goods_id in ($goodsID) AND (attr_value='".$sizestr."') AND attr_id = 2 )");
					  $date = $query->result_array();
					foreach($date as $key=>$rsdb){
						
					if($rsdb["goods_id"]){
						$attgoods = $rsdb["goods_id"];
						$Nrsdb = $this->fun->getdatabasesdetail("db_goods_attr"," AND goods_id ='".$attgoods."' AND (attr_value='".$sex."' or attr_value='通用') AND attr_id = 1");
						$modersdb = $this->fun->getdatabasesdetail("db_goods_attr"," AND goods_id ='".$attgoods."' AND (attr_value='".$model."' or attr_value='通用') AND attr_id = 9");
						if($Nrsdb && $modersdb)
						{
							$goodslist = $this->fun->getdatabasesdetail("db_goods"," AND goods_id ='".$attgoods."'","goods_sku,bulkprice,g_costprice");
							$msg['code'] = 201;
							$msg['linksku']  = $goodslist["goods_sku"];
							$msg['costprice']  = $goodslist["bulkprice"]?$goodslist["bulkprice"]:$goodslist["g_costprice"];
							$msg['factory_order_id'] = $orderid;
							$msg['tradeid'] = $tradeid;
							$msg['sku'] = $sku;
							$msg['goods_id'] = $attgoods;
							return $msg;
						}

					}else{
						return false;
					}

					}
				}

			}else{
				return false;
			}
		}else{
			return false;
		}
	}

	/**
	  +----------------------------------------------------------
	 * 判断子SKU是否存在在关联SKU
	  +----------------------------------------------------------
	 * @param cognatelist  子SKU
	 * @param goods_id     SKU ID 
	  +----------------------------------------------------------
	 * @return bool
	  +----------------------------------------------------------
	 */
	public function iscognatelist($cognatelist,$goods_id=0)
	{
		if(!$cognatelist)return;
		
		$cognatelist =trim($cognatelist,",");
		$cognatelist = array_filter(explode(",",$cognatelist));
		if($goods_id)
		{
			$where = " AND goods_id !='".$goods_id."'"; 
		}
		foreach($cognatelist  as $key=>$rs)
		{
			if($rs ==",")
			{
				continue;
			}
			$goodsinfo = $this->fun->getdatabasesdetail('db_goods'," AND goods_sku = '".$rs."' $where");
			if($goodsinfo)
			{
				return $rs."已经是SKU！不能成为子SKU,请修改后再保存";
			}
			$goodsinstfo = $this->fun->getdatabasesdetail('db_goods'," AND cognatelist like '%,".$rs.",%' $where");
			if($goodsinstfo)
			{
				return $rs."已经是别的商品[{$goodsinstfo[goods_sku]}]的子SKU，不能添加,请修改后再保存";
			}
		}
		return false;
	}
	
	/**
	  +----------------------------------------------------------
	 * 获得海外FBA产品的运输成本
	  +----------------------------------------------------------
	 * 1、系统中设立三个运输成本：海运成本、空运成本、平均成本；
	   2、其中空运成本是根据单个店铺的空运成本核算。如：订单核算时同一个SKU 在Carnival 运输成本10RMB，Costhat需要8RMB，根据店铺的运输任务核算
	   3、如果无法获得店铺的空运成本，使用平均成本
	@  
	  +----------------------------------------------------------
	 * @return int
	  +----------------------------------------------------------
	 */
	public function get_oversea_express_costprice($sku,$shopname='',$destination='')
	{
		$avgprice = 0;
		$sql_log = "SELECT count(goods_sku) as count,sum(price) as totalprice FROM t_transportlist_log WHERE goods_sku = '".$sku."' GROUP BY goods_sku ";
		$rs_log  = $this->db->query($sql_log)->row_array();
		if($rs_log){
			$avgprice = round($rs_log['totalprice']/$rs_log['count'],2);	//平均
		}
		if($shopname)	//按店铺
		{
			$sql_log = "SELECT count(goods_sku) as count,sum(price) as totalprice FROM t_transportlist_log WHERE goods_sku = '".$sku."'  AND shopname = '".$shopname."' GROUP BY goods_sku ";

			$rs_log  = $this->db->query($sql_log)->row_array();
			if($rs_log){
				$Newavgprice = round($rs_log['totalprice']/$rs_log['count'],2);
			}else{
				$Newavgprice = $avgprice;
			}
			return $Newavgprice;

		}
		if($destination)	//按目的地
		{
			$sql_log = "SELECT count(goods_sku) as count,sum(price) as totalprice FROM t_transportlist_log WHERE goods_sku = '".$sku."'  AND destination = '".$destination."' GROUP BY goods_sku ";
			$rs_log  = $this->db->query($sql_log)->row_array();
			if($rs_log){
				$destinationavgprice = round($rs_log['totalprice']/$rs_log['count'],2);
			}else{
				$destinationavgprice = $avgprice;
			}
			return $destinationavgprice;

		}
		return $avgprice;
	}
	/**
	  +----------------------------------------------------------
	 * 改变了长宽高之后重新计算头程
	  +----------------------------------------------------------
	@  
	  +----------------------------------------------------------
	 * @return int
	  +----------------------------------------------------------
	 */
	 public function again_oversea_express_costprice($sku)
	{
		$list = $this->db->get_where("t_transportlist_log","goods_sku = '".trim($sku)."'")->result_array();
	
		if(count($list)>0)
		{
			$totalprice = 0;
			foreach($list as $key=>$res){
				 $rsdb = $this->db->get_one("SELECT tasknumber,id,shopname,destination,freight,actual_freight,totalmoney,totalamount FROM t_transportationtask where status = 5 AND (freight >0 or actual_freight >0) and id='".$res['taskId']."'");
				 if($rsdb)
				 {
					
					if($rsdb["actual_freight"])	//计算总运费成本
					{
						$deliver_totalfee = $rsdb['actual_freight'] + $rsdb['totalmoney']; //预估费用+包装成本（多个箱子成本）
					}else{
						$deliver_totalfee = $rsdb['freight'] + $rsdb['totalmoney']; //预估费用+包装成本（多个箱子成本）
					}
					
					$rsbox = $this->db->get_one("SELECT sum(weight) as totalweight from t_transportbox where task_id = '".$res["taskId"]."'");
					$deliver_totalweight = $rsbox['totalweight'];//总重量
					
					if($deliver_totalweight)
					{
						$unitfee = round($deliver_totalfee/$deliver_totalweight,2);//计算每千克费用
					}
						
					if($unitfee)
					{
						$rsdbgoods = $this->fun->getdatabasesdetail('t_overseaproduct A LEFT JOIN db_goods B on A.sku = B.goods_sku'," AND sku='".$sku."'","A.*,B.g_weight");
						$db_weight = $rsdbgoods['g_weight'] /1000; //db_goods 重量为g，转换单位kg
						$real_weight = round(($rsdbgoods['lengthnum']*$rsdbgoods['widthnum']*$rsdbgoods['heightnum'])/6000,2);//保留两位小数
						if($db_weight>=$real_weight){
							$weight = $db_weight;
						}else{
							$weight = $real_weight;	//商品的重量
						}
						$deliver_costprice = $unitfee*$weight; //实际运输成本
						$deliver_costprice= round($deliver_costprice,2);
						$totalprice = $totalprice +$deliver_costprice;
						$counts = $res["transport_frequency"];
						$avgprice = round($totalprice/$counts,2);
						$this->db->update("t_transportlist_log",array('price'=>$deliver_costprice,"avgPrice"=>$avgprice),"id = '".$res['id']."'");
						$this->db->update('t_overseaproduct',array('deliverprice'=>$avgprice),"id = '".$rsdbgoods['id']."'");
						//修改以前的订单头程
						$this->db->update('db_amzordertmpsell',array('deliverprice'=>$avgprice),"productid = '".$sku."'");

					}
					
				 }
			}
		

		}
	 }


	/**
	  +----------------------------------------------------------
	 * 订单预估运费计算
	  +----------------------------------------------------------
	 * @param weight   重量 克
	 * @param country  国家 中文
	 * @param expresstypeid 物流ID or expressname 物流名称
	  +----------------------------------------------------------
	 * @return int
	  +----------------------------------------------------------
	 */
	
	public function get_Estimate_freight($weight,$country,$expresstypeid=0,$expressname='')
	{
		$pid = intval($expresstypeid);

		
		$country = trim($country);
		$expressname = trim($expressname);
		if(!$pid && !$expressname)
		{
			return "马帮物流ID号为空";
		}
		
		$rsdb = $this->getdatabasesdetail("db_order_express"," AND	(name = '".$expressname."' or id='".$expresstypeid."')");

		if($rsdb)
		{
			
			if($rsdb["id"]==14 && $country=='澳大利亚')	//如果是UBI并且是澳大利亚则执行另外澳大利亚单独的计算方式
			{
				return $price = $this->get_Estimate_freight_UBI($weight);
			}
			if($rsdb["discount"]==0)$rsdb["discount"]=1;	//如果是0折，默认改成不折扣，有可能是物流人员忘记填写折扣
			
			if($rsdb["types"] == 2)
			{
				//按克计算运费
				$expressprice =$this->getdatabasesdetail("db_order_express_formula","  AND	expresstypeid='".$rsdb["id"]."' AND country like '%".$country."%'");
				if($expressprice)
				{
					//如果有首重则以另外的计算公式
					if($expressprice['baseweight']>0)
					{
						if($weight<=$expressprice['baseweight'])	//小于首重50克
						{
							return $price = $expressprice['basemoney']; //都以基础金额计算
						}else{
							$newprice = $weight - $expressprice['baseweight']; //先减去一个首重
							if($expressprice['unitweight']>0)
							{
								$fee1 = intval($newprice / $expressprice['unitweight']);//减去之后的重量除以续重
							}else{
								$fee1 =0;
							}
							if($expressprice['unitweight']>0)
							{
								$fee2 = $newprice % $expressprice['unitweight'];
							}else{
								$fee2 =0;
							}
							if($fee2==0){
								return $price =  ($fee1 * $expressprice['unitmoney']) +$expressprice['basemoney'];	//续重费用
							}else{
								return $price =  ($fee1 * $expressprice['unitmoney']) +$expressprice['basemoney']+$expressprice['unitmoney'];	//续重费用
							}
						}
						
					}else{
						return $price = round(($weight * $expressprice["basemoney"])*$rsdb["discount"] + $expressprice["reserve6"],2);
					}
				}else{
					return "没有填写运费计算公式";
				}
			}else{
				//按区计算
				//先重量计算出运费档位
				$fee1 = intval($weight / 500);
				$fee2 = $weight % 500;
				if($fee2==0){
					$goods_weight =  $fee1 * 0.5*1000;
				}else{
					$goods_weight =  ($fee1 * 0.5+0.5)*1000;
				}
				$newex =$this->getdatabasesdetail("db_order_express_formula","  AND	expresstypeid='".$rsdb["id"]."' AND country like '%".$country."%'");
				if($newex)
				{
					
					$expressprice_price=$this->getdatabasesdetail("db_order_express_formula_price","  AND formula_id='".$newex["id"]."' AND weight = $goods_weight");
					if($expressprice_price)
					{
						if($expressprice_price['price']>0)
						{
						 return	$price = round($expressprice_price['price']* $rsdb["discount"],2);
						}else
							return "没有填写运费计算公式";
					}else{
						return "没有填写运费计算公式";
					}

				}else{
					return "没有填写运费计算公式";
				}
			
			}
			
		}else{
			return "没有填写运费计算公式";
		}

	}

	function get_Estimate_freight_UBI($weight){

		if($weight<=1000){	//1000克 以下 10的克计算
			$jit = 10;
		}elseif($weight<=10000) //1000克 以下 10的克计算
		{
			$jit = 100;
		}
		elseif($weight<=30000)
		{
			$jit = 500;
		}
		if($weight<50)
		{
			$fee1 = $fee2 = 0;
			$goods_weight = 50;
		}else{
			$fee1 = intval($weight / $jit);	
			$fee2 = $weight % $jit;
			if($fee2==0){
				$goods_weight =  $fee1 * $jit;
			}else{
				$goods_weight =  ($fee1 * $jit+$jit);
			}
		}
		if($goods_weight)
		{
			$rs = $this->getdatabasesdetail("db_order_express_ubi"," AND weight='".$goods_weight."'");
			if($rs)
			{
				return $rs['price'];
			}else{
				return "没有填写运费计算公式";
			}
		}
	}
	/**
	  +----------------------------------------------------------
	 * 获取历史销售
	  +----------------------------------------------------------
	 * @param goods SKU
	 * @param startime  开始时间(同期时间)
	 * @param endtime  结束时间
	  +----------------------------------------------------------
	 * @return int function_M.php goods_history_sales
	  +----------------------------------------------------------
	 */
	function goods_history_sales($goods,$startime,$endtime)
	{
	
		if(strtotime($startime) >= strtotime('2017-08-01'))
		{
			//时间大于2017年8月15，马帮没数据了，要去新系统
			$sql = "SELECT SUM(goods_number) AS goods_number from db_order_sell A LEFT JOIN db_order_list B on A.order_id = B.order_id where B.order_status in(4,5) and A.goods_sn = '{$goods}' and B.dates <='".$endtime."' AND B.dates >='".$startime."'";
			$res = $this->db->get_one($sql);
			$sql_amazon = "SELECT SUM(ordernum) AS goods_number from db_amzordertmpsell A LEFT JOIN db_amzordertmp B on A.ordertmpid = B.id where  A.productid = '{$goods}' and B.dates <='".$endtime."' AND B.dates >='".$startime."'";
			$res_amazon = $this->db->get_one($sql_amazon);
			$all_num = $res['goods_number']+$res_amazon['goods_number'];
			return $all_num;
		}else{
			$this->load->library('Mabang');
			$nums = $this->mabang->getskusell($goods,$startime,$endtime);//读取去年马帮的同时间统计信息
			return $nums;
		}
	}

	/**
	  +----------------------------------------------------------
	 * 获取维护人员的ID
	  +----------------------------------------------------------
	 * @param classid 部份
	 * @param userid  接收用户
	 * @param rsdb  商品信息
	  +----------------------------------------------------------
	 * @return int
	  +----------------------------------------------------------
	 */

	function getexternal_user($classid,$userid,$rsdb='')
	{
			$p_buyer = 9999;	//曾月
			if($classid == 3 || $classid ==2)	//德语销售部,欧美销售部 推荐的给姜
			{
				$p_buyer = "7777";//姜
			}
			if($classid == 6)	//德语销售部,欧美销售部 推荐的给姜
			{
				$p_buyer = "8888";//陈飞
			}
			if($userid == 336 || $userid==243)	//西班牙
			{
				$p_buyer = "7777";//姜
			}
			$arraycookie=array(368,107,119,175,219,282,334,335);
			if(in_array($userid,$arraycookie))	//西班牙
			{
				$p_buyer = "9999";//曾月
			}
			if( strpos($rsdb["goods_name"],'鞋') !== false || strpos($rsdb["goods_name"],'假发') !== false  )
			{
				//$p_buyer = "6666";//高菲菲
			}

			return $p_buyer;
	 
	 }

	 /**
	  +----------------------------------------------------------
	 * 网站或者Ebay自动上架成功之后，自动更新新品开发、外采中的
	 * 商品信息
	  +----------------------------------------------------------
	 * @param sku  需要上架的SKU
	 * @param userid  接收用户
	  +----------------------------------------------------------
	 * @return int
	  +----------------------------------------------------------
	 */


	public function update_develop_addtime($sku,$userid,$url,$flag=1)
	{
		//正向开发
		$rs = $this->fun->getdatabasesdetail("db_product_develop"," and sku='".trim($sku)."' AND receivers like '%,".$userid.",%' and return_receivers NOT REGEXP  '".$userid."' ");
		if($rs)
		{
			$reason = $userid."-".$flag."-".$url;
			if($rs['return_reason']){
				$ret_reason = $rs['return_reason'].",".$reason;
			}else{
				$ret_reason = $reason;
			}
			if($rs['return_receivers']){
				$ret_receivers = $rs['return_receivers'].",".$userid;
			}else{
				$ret_receivers = $userid;
			}
			$this->db->update("db_product_develop",array('return_receivers'=>$ret_receivers,'return_reason'=>$ret_reason)," id = '".$rs['id']."'");
			$username = $this->userinfo($userid);
			//记录上架时间 或 取消上架时间
			$arr_shelf = array();
			$arr_shelf['develop_id'] = $rs['id'];
			$arr_shelf['sku'] = $rs['sku'];
			$arr_shelf['type'] = 1;
			$arr_shelf['linkUrl'] = $url;
			$arr_shelf['createUid'] = $userid;
			$arr_shelf['createUser'] = $username['name'];
			$arr_shelf['addTime'] = date("Y-m-d H:i:s");
			$this->db->insert("db_product_develop_addtime",$arr_shelf); //插入数据不更新
		}
		
		//逆向开发
		$rsdb = $this->fun->getdatabasesdetail("db_external_buy"," and sku='".trim($sku)."' AND receivers like '%,".$userid.",%' and return_receivers NOT REGEXP  '".$userid."' ");
		if($rsdb)
		{
			$reason = $userid."-".$flag."-".$url;
			if($rsdb['return_reason']){
				$ret_reason = $rsdb['return_reason'].",".$reason;
			}else{
				$ret_reason = $reason;
			}
			if($rsdb['return_receivers']){
				$ret_receivers = $rsdb['return_receivers'].",".$userid;
			}else{
				$ret_receivers = $userid;
			}
			$this->db->update("db_external_buy",array('return_receivers'=>$ret_receivers,'return_reason'=>$ret_reason)," id = '".$rsdb['id']."'");
		}

	}



}

/* End of file welcome.php */
/* Location: ./application/controllers/welcome.php */